import mqtt from 'mqtt'
// import { moveToCenterByLonAndLat } from "./util";
export default {
  data() {
    return {
      connection: {
        // host: '47.110.162.166',
        // port: 8083,
        host: "47.96.65.45",
        port: 8083,
        connectTimeout: 4000, // 超时时间
        reconnectPeriod: 4000, // 重连时间间隔
        // keepAlive: 60,
        // clientId: 'mqttjs_' + Math.random().toString(16).substr(2, 8),
        username: 'admin',
        password: 'public',
        // transports: ['websocket']
      },
      client: {
        connected: false,
      },
      topicList: [
        {
          topic: "/udp/image",
          fn: "getImage"
        },
        {
          topic: "STATE",
          fn: "getCenter"
        },
        {
          topic: "ARPA",
          fn: "getARPA"
        },
        {
          topic: "REMOVE",
          fn: "deleteShip"
        }
      ]
    }
  },
  computed: {
    topicEvent() {
      let obj = {}
      for (let item of this.topicList) {
        obj[item.topic] = item.fn
      }
      return obj
    }
  },
  methods: {
    Uint8ArrayToString(fileData) {
      var dataString = "";
      for (var i = 0; i < fileData.length; i++) {
        dataString += String.fromCharCode(fileData[i]);
      }
      return dataString
    },
    // 创建连接
    createConnection() {
      const { host, port, ...options } = this.connection
      const connectUrl = `mqtt://${host}:${port}/mqtt`
      // const connectUrl = `ws://${host}:${port}`
      try {
        this.client = mqtt.connect(connectUrl, options)
      } catch (error) {
        console.log('mqtt.connect error', error)
      }
      this.client.on('connect', () => {
        console.log('Connection succeeded!')
        for (let item of this.topicList) {
          this.client.subscribe(item.topic, (err) => {
            if (!err) {
              console.log("订阅成功");
            }
          });
        }
      })
      this.client.on('error', error => {
        console.log('Connection failed', error)
      })
      this.client.on('message', (topic, message) => {
        this[this.topicEvent[topic]](message)
      })
    },
    getImage(message) {
      if (!this.radarShowOptions.waveShow) return
      const blob = new Blob([message], {
        type: "application/png;charset=utf-8"
      });
      const url = window.URL.createObjectURL(blob);
      if (!this.radarOptions) return;
      // 渲染完新的图层后删除到之前的图层
      let newLayerName = `radar-${+new Date()}`
      // 渲染
      this.map.addLayer(this.initImage(url, newLayerName))
      setTimeout(() => {
        if (this.radarLayerName) {
          let layerTmp = this.map.getLayers().getArray().find(m => m.get("name") === this.radarLayerName)
          if (layerTmp) this.map.removeLayer(layerTmp)
        }
        this.radarLayerName = newLayerName
      }, 100);
    },
    getCenter(message) {
      const row = JSON.parse(this.Uint8ArrayToString(message))
      if (!this.radarOptions) {
        // 首次接收到数据， 移动到雷达点处
        // moveToCenterByLonAndLat([row.lon, row.lat], this.map)
      }
      this.radarOptions = {
        center: [row.lon, row.lat],
        range: row.range / 450 * 1024 * 1852,
        data: row
      }
    },
    // 船舶不同类型显示 
    shipShow(row) {
      let shipData = {}
      if (row.arpaType === "1") {
        shipData = {
          data: row,
          targetNum: "AIS" + row.aisMmsi,
          lon: row.aisLon,
          lat: row.aisLat,
          course: row.aisCog,
          shipName: row.aisShipName,
          mmsi: row.aisMmsi || null,
          arpaType: row.arpaType
        }
      } else {
        shipData = {
          data: row,
          targetNum: row.targetNum,
          lon: row.targetLon,
          lat: row.targetLat,
          course: row.targetRcourse,
          shipName: row.aisShipName,
          mmsi: row.aisMmsi || null,
          arpaType: row.arpaType
        }
      }
      this.handleDrawShip(shipData)
      // 判断是否选中，更新详情框中的信息
      if (shipData.targetNum === this.shipDetailInfo.targetNum) {
        this.$set(this, "shipDetailInfo", shipData)
      }
    },
    // arpa
    shipShow0(row) {
      let shipData = {}
      if (row.arpaType === "0" || row.arpaType === "2") {
        shipData = {
          data: row,
          targetNum: row.targetNum,
          lon: row.targetLon,
          lat: row.targetLat,
          course: row.targetRcourse,
          shipName: row.aisShipName,
          mmsi: row.aisMmsi || null,
          arpaType: "0"
        }
      }
      this.handleDrawShip(shipData)
      // 判断是否选中，更新详情框中的信息
      if (shipData.targetNum === this.shipDetailInfo.targetNum) {
        this.$set(this, "shipDetailInfo", shipData)
      }
    },
    // AIS
    shipShow1(row) {
      let shipData = {}
      if (row.arpaType === "1") {
        shipData = {
          data: row,
          targetNum: "AIS" + row.aisMmsi,
          lon: row.aisLon,
          lat: row.aisLat,
          course: row.aisCog,
          shipName: row.aisShipName,
          mmsi: row.aisMmsi || null,
          arpaType: row.arpaType
        }
        this.handleDrawShip(shipData)
        // 判断是否选中，更新详情框中的信息
        if (shipData.targetNum === this.shipDetailInfo.targetNum) {
          this.$set(this, "shipDetailInfo", shipData)
        }
      }
    },
    // 融合后
    shipShow2(row) {
      let shipData = {}
      if (row.arpaType === "2") {
        shipData = {
          data: row,
          targetNum: row.targetNum,
          lon: row.targetLon,
          lat: row.targetLat,
          course: row.targetRcourse,
          shipName: row.aisShipName,
          mmsi: row.aisMmsi || null,
          arpaType: row.arpaType
        }
      }
      this.handleDrawShip(shipData)
      // 判断是否选中，更新详情框中的信息
      if (shipData.targetNum === this.shipDetailInfo.targetNum) {
        this.$set(this, "shipDetailInfo", shipData)
      }
    },
    // 融合前
    shipShow3(row) {
      if (row.arpaType === "2") {
        const AISShipData = {
          data: row,
          targetNum: "AIS" + row.aisMmsi,
          lon: row.aisLon,
          lat: row.aisLat,
          course: row.aisCog,
          shipName: row.aisShipName,
          mmsi: row.aisMmsi || null,
          arpaType: "1"
        }
        const ARPAShipData = {
          data: row,
          targetNum: row.targetNum,
          lon: row.targetLon,
          lat: row.targetLat,
          course: row.targetRcourse,
          shipName: row.aisShipName,
          mmsi: row.aisMmsi || null,
          arpaType: "0"
        }
        this.handleDrawShip(AISShipData)
        this.handleDrawShip(ARPAShipData)
        // 判断是否选中，更新详情框中的信息
        if (AISShipData.targetNum === this.shipDetailInfo.targetNum) {
          this.$set(this, "shipDetailInfo", AISShipData)
        }
        if (ARPAShipData.targetNum === this.shipDetailInfo.targetNum) {
          this.$set(this, "shipDetailInfo", ARPAShipData)
        }
      }
    },
    getARPA(message) {
      const row = JSON.parse(this.Uint8ArrayToString(message))
      // 0 arpa  1 AIS  2 融合后 3 融合前
      if (this.shipShowType === 0) {
        this.shipShow0(row)
      } else if (this.shipShowType === 1) {
        this.shipShow1(row)
      } else if (this.shipShowType === 2) {
        this.shipShow2(row)
      } else if (this.shipShowType === 3) {
        this.shipShow3(row)
      } else {
        this.shipShow(row)
      }
    },
    deleteShip(message) {
      const row = JSON.parse(this.Uint8ArrayToString(message))
      this.deleteShipById(row)
    }
  },
  created() {
    this.createConnection()
  }
}
